package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.mapper.CategoryBrandMapper;
import com.spzx.product.service.BrandService;
import com.spzx.product.service.CategoryBrandService;
import com.spzx.product.service.CategoryService;
import com.spzx.product.api.domain.Category;
import com.spzx.product.api.domain.CategoryBrand;
import com.spzx.product.api.domain.vo.CategoryBrandVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand>
        implements CategoryBrandService {

    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;

    @Override
    public List<CategoryBrandVo> categoryBrandInfoList(CategoryBrand categoryBrand) {
        return baseMapper.categoryBrandInfoList(categoryBrand);
    }

    @Override
    public void checkCategoryBrandUnique(CategoryBrand categoryBrand) {
        Long id = categoryBrand.getId();
        if (id == null) {
            categoryBrand.setCreateBy(SecurityUtils.getUsername());
        } else {
            categoryBrand.setUpdateBy(SecurityUtils.getUsername());
        }
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<CategoryBrand>()
                .eq(CategoryBrand::getBrandId, categoryBrand.getBrandId())
                .eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId()));

        if (count > 0) {
            throw new ServiceException("分类品牌已存在");
        }
    }

    @Override
    public CategoryBrandVo getCategoryBrandVoById(Long id) {
        CategoryBrand categoryBrand = getById(id);
        Long categoryId = categoryBrand.getCategoryId();
        List<Long> categoryIdList = getAllParentIds(categoryId, new ArrayList<Long>());
        Collections.reverse(categoryIdList);
        CategoryBrandVo categoryBrandVo = new CategoryBrandVo();
        BeanUtils.copyProperties(categoryBrand, categoryBrandVo);
        categoryBrandVo.setBrandName(brandService.getById(categoryBrand.getBrandId()).getName());
        categoryBrandVo.setCategoryIdList(categoryIdList);
        return categoryBrandVo;
    }

    public List<Long> getAllParentIds(Long id, ArrayList<Long> longs) {
        while (id > 0) {
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getId, id));
            longs.add(id);
            return getAllParentIds(category.getParentId(), longs);
        }
        return longs;
    }
}




